package controllers

import play.api._
import play.api.mvc._
import play.libs.Json
import elastic.Tracer

object Application extends Controller with XHR {
  
  val searchImplementationName = play.api.Play.current.configuration.getString("searchImplementation").getOrElse("elastic.RUCUpdater")
  val clazz = Class.forName(searchImplementationName)
  val indexer = clazz.newInstance().asInstanceOf[service.RUCUpdater]

  def findRuc(ruc: String) = XhrAction { implicit request =>
    Logger.info("findRuc: " + ruc)
    val res = if (ruc.head.isDigit) {
      val index = if (ruc.indexOf("-") == -1) ruc.length() else ruc.indexOf("-")
      indexer.findRuc(ruc.substring(0, index))
    } else {
      indexer.findContribuyente(ruc)
    }
    Logger.info("res: " + res)
//    logAccess(request, res)
    Ok(res._1).as(JSON)
  }
  
  def logAccess(request: Request[AnyContent], res: (String, Long, Long)) = {
//  def logAccess(request: Request[AnyContent], ruc: String, found: Long, responseTime: Long) = {
    Logger.info("logAccess")
    
    Tracer.trace(res._1, res._2, res._3, request.remoteAddress)
  }

  def update = Action {
    try {
//      indexer.update()
        BadRequest("no no")
//      Ok("ok")
    } catch {
      case e: Exception => {
        Logger.error(e.toString())
//        respondText(e.getMessage())
        BadRequest(e.getMessage())
      }
    }
  }
}